#include "SimpleTcpConnection.h"
#include "SimpleTcpServer.h"
#include "RequestHandler.h"
#include "RequestParser.h"


using namespace boost::asio;
using namespace std;
using namespace tbb;


SimpleTcpConnection::SimpleTcpConnection(io_service &ioService)
	: _socket(ioService)
{
	//
}

void SimpleTcpConnection::StartParsing()
{
	boost::tribool result;

	do
	{
		boost::system::error_code e;
		size_t bytesTransferred = _socket.read_some(buffer(_buffer), e);

		if (e)
		{
			return;
		}

		boost::tie(result, boost::tuples::ignore) = _requestParser.Parse(_request, _buffer.data(),
																			_buffer.data() + bytesTransferred);
	}
	while (indeterminate(result));

	if (result)
	{
		RequestHandler::HandleRequest(_request, _reply);

		write(_socket, _reply.ToBuffers());
	}
	else
	{
		_reply = Reply::StockReply(Reply::BadRequest);
		write(_socket, _reply.ToBuffers());
	}

	delete this;
}
